package org.ohos.rajawali3d.examples;

import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.ability.fraction.FractionAbility;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.IntentParams;
import org.ohos.rajawali3d.ResourceTable;
import org.ohos.rajawali3d.examples.data.RajawaBean;
import org.ohos.rajawali3d.examples.examples.AExampleFragment2;

public class ExamplesAbility2 extends FractionAbility {

    public static final String EXTRA_EXAMPLE_URL = "EXTRA_EXAMPLE_URL";
    public static final String EXTRA_EXAMPLE_CLASS = "EXTRA_EXAMPLE_CLASS";
    public static final String EXTRA_EXAMPLE_TYPE = "EXTRA_EXAMPLE_TYPE";
    ;
    public static final String EXTRA_EXAMPLE_NAME = "EXTRA_EXAMPLE_NAME";
    ;

    @Override
    protected void onStart(Intent savedInstanceState) {
        super.onStart(savedInstanceState);
        setUIContent(ResourceTable.Layout_activity_examples);

        if (savedInstanceState != null) {
            Intent intent = getIntent();
            if (intent != null) {
                IntentParams extras = intent.getParams();
                if (extras != null) {
                    processExtras(extras);
                }
            }
        }
    }

    private void processExtras(IntentParams extras) {
        String url = (String) extras.getParam(EXTRA_EXAMPLE_URL);
        String class_name = (String) extras.getParam(EXTRA_EXAMPLE_CLASS);
        int type = (int) extras.getParam(EXTRA_EXAMPLE_TYPE);
        int name = (int) extras.getParam(EXTRA_EXAMPLE_NAME);
        String path = (String) extras.getParam(ExamplesAbility.EXTRA_EXAMPLE_PATH);
        Class aCl;
        try {
            aCl = Class.forName(class_name);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return;
        }
        RajawaBean example = new RajawaBean(name, type, aCl, url, path);

        Class aClass = example.getExampleClass();

        try {
            IntentParams bundle = new IntentParams();
            bundle.setParam(AExampleFragment2.BUNDLE_EXAMPLE_URL, example.getUrl());

            Fraction fragment = (Fraction) aClass.newInstance();
            fragment.getFractionAbility().setIntent((new Intent()).setParams(bundle));

            getFractionManager().startFractionScheduler().replace(ResourceTable.Id_content_frame, fragment)
                    .submit();
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }

}
